package com.corpgovernment.future;






import com.corpgovernment.common.utils.ObjectStringTrimUtils;
import com.google.common.util.concurrent.*;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.remoting.InvokeCallback;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.remoting.netty.ResponseFuture;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.*;

public class CompletableFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {



        ExecutorService executor = Executors.newFixedThreadPool(2);
        ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(executor);

        ListenableFuture<String> future = listeningExecutor.submit(() -> {
            Thread.sleep(15000); // 模拟耗时操作
            return "Task1 completed";
        });

        ListenableFuture<String> future2 = listeningExecutor.submit(() -> {
            Thread.sleep(15000); // 模拟耗时操作
            return "Task2 completed";
        });

        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        ListenableFuture<String> timeoutFuture = Futures.withTimeout(future, 1, TimeUnit.SECONDS, scheduler);

        ListenableFuture<String> timeoutFuture2 = Futures.withTimeout(future2, 10, TimeUnit.SECONDS, scheduler);
        System.out.println("Active Threads: " + ( executor));
        Futures.addCallback(timeoutFuture, new FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println(result);
            }

            @Override
            public void onFailure(Throwable t) {
                if (t instanceof TimeoutException) {
                    System.out.println("Task1 timed out");
                    // 在需要的时候取消超时任务
                    //timeoutFuture.cancel(true);
                } else {
                    t.printStackTrace();
                }
            }
        }, listeningExecutor);

        Futures.addCallback(timeoutFuture2, new FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println(result);
            }

            @Override
            public void onFailure(Throwable t) {
                if (t instanceof TimeoutException) {
                    System.out.println("Task2 timed out");
                    // 在需要的时候取消超时任务
                    //timeoutFuture2.cancel(true);
                } else {
                    t.printStackTrace();
                }
            }
        }, listeningExecutor);

        Thread.sleep(2000);
        System.out.println("Active Threads: " + ( executor));

        Thread.sleep(10000);
        System.out.println("Active Threads: " + ( executor));

        System.out.println("Active Threads: " + ((ThreadPoolExecutor) executor).getActiveCount());

        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        ThreadInfo[] threadInfos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), Integer.MAX_VALUE);

        for (ThreadInfo info : threadInfos) {
            System.out.println("[" + info.getThreadId() + "] " + info.getThreadName() + " - " + info.getThreadState());
        }

        //listeningExecutor.shutdown();
        //scheduler.shutdown();

    }


    private static int calculateResult(int number) {

        if (number == 3) {
            throw new RuntimeException("Error occurred for number: " + number);
        }
        try {
            Thread.sleep(2000);
            return number * 2;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
